/*
 * @Author: your name
 * @Date: 2021-09-23 15:50:42
 * @LastEditTime: 2023-11-15 23:48:09
 * @LastEditors: wuqiang
 * @Description: In User Settings Edit
 * @FilePath: /blog/Users/wuqiang/workspace/huijun-frontend/src/utils/index.ts
 */
import {PHONE_REGEXP, IDCARD_REGEXP, EMAIL_REGEXP} from '@/constants';
import { useRef } from 'react';

function getStartInsuranceDate() {
  let year = new Date().getFullYear();
  let month = new Date().getMonth() + 1;
  let date = new Date().getDate();
  let todayMiliSecond = new Date(`${year}/${month}/${date}`).getTime() + 24 * 3600 * 1000;
  let _tYear = new Date(todayMiliSecond).getFullYear();
  let _tMonth = new Date(todayMiliSecond).getMonth() + 1;
  let _tDate = new Date(todayMiliSecond).getDate();
  return `${_tYear}/${_tMonth}/${_tDate}`;
}

function getStopInsuranceDate() {
  let arr = getStartInsuranceDate().split('/')
  let year = parseInt(arr[0]) + 1;
  let _tMiliSeconds = new Date(`${year}/${arr[1]}/${arr[2]}`).getTime() - 1000;
  let _tYear = new Date(_tMiliSeconds).getFullYear();
  let _tMonth = new Date(_tMiliSeconds).getMonth() + 1;
  let _tDate = new Date().getDate();
  return `${_tYear}/${_tMonth}/${_tDate}`;
}

function isValidName(param) {
  return param && param.trim() && param.trim().length >= 2;
}

function isValidEmail(param) {
  return EMAIL_REGEXP.test(param);
}

function isValidPhone(param) {
  return PHONE_REGEXP.test(param);
}

function isValidIdCard(param) {
  return IDCARD_REGEXP.test(param);
}

function getAge(identifyNumber, time?: number) {
  if(isValidIdCard(identifyNumber)) {
    let year = parseInt(identifyNumber.substr(6, 4));
    let month = parseInt(identifyNumber.substr(10, 2));
    let date = parseInt(identifyNumber.substr(12, 2));
    let _time = time ? new Date(time) : new Date();
    let age = _time.getFullYear() - year;
    let _curMonth = _time.getMonth() + 1;
    let _curDate = _time.getDate();

    if(_curMonth < month) {
      --age;
    } else if(_curMonth === month) {
      if(_curDate < date) {
        --age
      }
    }
    return age;
  } else {
    return null
  }
}

function checkDistance(id) {
  let ele: any = document.getElementById(id);
  let top = ele.getBoundingClientRect().top;
  let height = document.documentElement.clientHeight || document.body.clientHeight;
  if(top > height) {
    ele.scrollIntoView();
    return false;
  } else {
    return true;
  }
}

function useDebounce<T extends unknown[]>(fn: (...args:T) => unknown, delay: number) {
  const ref = useRef<any>();
  return function callback(...args: T) {
    // @ts-ignore
    let that = this
    clearTimeout(ref.current)
    ref.current = setTimeout(() => fn.apply<any, T, unknown>(that, args), delay)
  }
}


export {
  getStartInsuranceDate,
  getStopInsuranceDate,
  isValidIdCard,
  isValidName,
  isValidPhone,
  isValidEmail,
  getAge,
  checkDistance,
  useDebounce,
}